package com.boy.controller.clip;

import com.boy.tool.utils.JwtUtils;
import com.boy.entity.Account;
import com.boy.entity.Permission;
import com.boy.service.AccountService;
import com.boy.tool.annotate.Arbitrarily;
import com.boy.tool.domain.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author whd
 * @date 2024/05/24 14:55:28
 */
@RestController
@RequestMapping("/clip/auth")
public class AuthController {

    @Autowired
    private AccountService accountService;

    @Arbitrarily
    @PostMapping("/login")
    public ResultVo login(@RequestParam(value = "phone") String phone, @RequestParam(value = "password") String password, HttpServletRequest request) {
        String ip = request.getRemoteAddr();
        Account account = accountService.login(phone, password, ip);
        String token = JwtUtils.getJwtToken(account.getId() + "", account.getPhone());
        return ResultVo.success("登录成功", token);
    }


    @PostMapping("/access")
    public ResultVo access(@RequestHeader("Authorization") String token) {
        String id = JwtUtils.getMemberIdByJwtToken(token);
        List<Permission> permissions = accountService.findPermission(id);
        return ResultVo.success(permissions);
    }

    @PostMapping("/me")
    public ResultVo me(@RequestHeader("Authorization") String token) {
        String id = JwtUtils.getMemberIdByJwtToken(token);
        Account account = accountService.getById(id);
        return ResultVo.success(account);
    }

    @Arbitrarily
    @PostMapping("/emailToken")
    public ResultVo emailToken(@RequestParam String email, @RequestParam String code, HttpServletRequest request) {
        String ip = request.getRemoteAddr();
        Account account = accountService.emailLogin(email, code, ip);
        String token = JwtUtils.getJwtToken(account.getId() + "", account.getPhone());
        return ResultVo.success("登录成功", token);
    }

}
